package com.tzbank.esb.util;

import com.dc.eai.data.CompositeData;
import com.dcfs.esb.client.ESBClient;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;
import java.util.Map;

@Slf4j
public class EsbConsumerUtil {

	/**
	 * ESB消费请求发送
	 * @return
	 */
	public static Map<String, Object> clientRequest(Map<String, Object> inputMap) {
		return ESBClientRequest(inputMap, false);
	}
	
	/**
	 * ESB消费请求发送
	 * @return
	 */
	public static Map<String, Object> clientRequestNoHead(Map<String, Object> inputMap) {
		return ESBClientRequest(inputMap, true);
	}
	
	/**
	 * ESB消费请求发送
	 * @param inputMap
	 * @return
	 */
	private static Map<String, Object> ESBClientRequest(Map<String, Object> inputMap,boolean removeFlag) {
		try {
			long beginTime = new Date().getTime();		//请求开始时间
			
			//Map转换Esb报文
			CompositeData reqCompositeData = EsbConversionUtil.mapToCompositeData(inputMap);		//对象转换
			//发送请求到ESB
			CompositeData respCompositeData = ESBClient.request(reqCompositeData);
			
			//通过核心所返回标志Code=000000来判断调用核心计价因子是否调用成功
			String code = (String) respCompositeData.getStruct("SYS_HEAD").getArray("RET").getStruct(0).getField("RET_CODE").getValue();
			
			//获取msg信息
			String msg = (String) respCompositeData.getStruct("SYS_HEAD").getArray("RET").getStruct(0).getField("RET_MSG").getValue();
			
			if (code != null && !code.equals("000000")) {
				return ResultUtil.resultMap(msg, code, null);
			}
			
			Map<String, Object> outputMap = EsbConversionUtil.compositeDataToMap(respCompositeData);		//Esb报文转换Map
			
			if(removeFlag) {
				outputMap.remove("head");		//去掉head信息
			}
			
			long endTime = new Date().getTime();		//请求结束时间
			log.info("==========================>ESB接口调用花费时长：" + (endTime - beginTime )  + "秒<==========================");
			outputMap.put("esbTime", (endTime - beginTime )+"毫秒");
			return ResultUtil.resultMap(CodeUtil.CODE_200.getName(), CodeUtil.CODE_200.getCode(), outputMap);
		} catch (Exception e) {
			log.info("ESB报文转换出错", e);
			return ResultUtil.resultMap(BusinessCodeUtil.CODE_40001.getName(), BusinessCodeUtil.CODE_40001.getCode(), null);
		}
	}
}
